package cn.steam.foo.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@WebFilter(filterName = "traceIdFilter", urlPatterns = "/*")
@Order(0)
@Component
public class TraceIdFilter extends HttpFilter {

    private final Logger logger = LoggerFactory.getLogger(TraceIdFilter.class);

    /**
     * 日志跟踪标识
     */
    public static final String TRACE_ID = "TRACE_ID";

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            MDC.put(TRACE_ID, getTraceId(request));
            response.addHeader(TRACE_ID, MDC.get(TRACE_ID));
            chain.doFilter(request, response);
        } finally {
            MDC.clear();
        }
    }

    private String getTraceId(HttpServletRequest request) {
        String paramRequestId = request.getParameter(TRACE_ID);
        String headerRequestId = request.getHeader(TRACE_ID);
        // 根据请求参数或请求头判断是否有“request-id”，有则使用，无则创建
        String requestId;
        if (paramRequestId == null && headerRequestId == null) {
            requestId = UUID.randomUUID().toString();
        } else {
            requestId = paramRequestId != null ? paramRequestId : headerRequestId;
        }
        return requestId;
    }
}